//
//  IDGWBViewController.m
//  Goodman Web Browser
//
//  Created by iD Student on 7/11/13.
//  Copyright (c) 2013 Apple Inc. All rights reserved.
//

#import "IDGWBViewController.h"

#import "IDGWBHistoryViewController.h"

@interface IDGWBViewController ()

@end

@implementation IDGWBViewController{
    NSString *addressToGo;
    
}

static const CGFloat kNavBarHeight = 52.0f;
static const CGFloat kLabelHeight = 14.0f;
static const CGFloat kMargin = 10.0f;
static const CGFloat kSpacer = 2.0f;
static const CGFloat kLabelFontSize = 12.0f;
static const CGFloat kAddressHeight = 26.0f;

@synthesize pageTitle = mPageTitle;

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    
    
    if([_suffixIsGood isEqual: @"YES"]){}
    
    else if([_suffixIsGood isEqual: @"NO"])
    {
        [_addressBar setText:[[webView.request URL] absoluteString]];
        [self setBackForwardButtonState];
    }
    [_addressBar setText:[[webView.request URL] absoluteString]];
    [_activity startAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self setBackForwardButtonState];
    
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString* pageTitle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.pageTitle.text = pageTitle;
    [self setBackForwardButtonState];
    if( ! [pageTitle isEqualToString:@""]){
        
    [_setHistory addObject:mPageTitle.text];
}

    if( ! [[[webView.request URL] absoluteString] isEqualToString:@""])
    [_setHistoryURLS addObject:_addressBar.text];
    NSLog(@"%@" , _setHistory.description);
    NSLog(@"%@" , _setHistoryURLS.description);
    [_activity stopAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}


- (void) viewWillAppear:(BOOL)animated
{
    NSURLRequest *request = [NSURLRequest requestWithURL:self.urlToLoad];
    [_webView loadRequest:request];
}

- (void)viewDidLoad
{
    self.pageTitle.text = @"Stainless Broswer";
    _setHistory = [[NSMutableSet alloc] init];
    _setHistoryURLS = [[NSMutableSet alloc] init];
    [self.webView addSubview: _activity];
    [self.view addSubview: _activity];
    [self.webView setDelegate:self];
    [super viewDidLoad];
    [_searchField setDelegate:self];
    [_addressBar setDelegate:self];

}



-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    if([_suffixIsGood isEqual: @"NO"])
        return NO;
    [_activity stopAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    return YES;
}





- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *stringURL = _addressBar.text;
    
    if([[stringURL uppercaseString] hasSuffix:@"COM"] || [[stringURL uppercaseString] hasSuffix:@".NET"] || [[stringURL uppercaseString] hasSuffix:@".ORG"]  || [[stringURL uppercaseString] hasSuffix:@".EDU"]  || [[stringURL uppercaseString] hasSuffix:@".NU"]  || [[stringURL uppercaseString] hasSuffix:@".SE"]  || [[stringURL uppercaseString] hasSuffix:@".US"]  || [[stringURL uppercaseString] hasSuffix:@".UK"]  || [[stringURL uppercaseString] hasSuffix:@".LY"] ){
        NSString *suffixIsGood = @"YES";
    }
    
    else if(![[stringURL uppercaseString] hasSuffix:@"COM"] || [[stringURL uppercaseString] hasSuffix:@".NET"] || [[stringURL uppercaseString] hasSuffix:@".ORG"]  || [[stringURL uppercaseString] hasSuffix:@".EDU"]  || [[stringURL uppercaseString] hasSuffix:@".NU"]  || [[stringURL uppercaseString] hasSuffix:@".SE"]  || [[stringURL uppercaseString] hasSuffix:@".US"]  || [[stringURL uppercaseString] hasSuffix:@".UK"]  || [[stringURL uppercaseString] hasSuffix:@".LY"] ){
            NSString *suffixIsGood = @"NO";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Stainless Browser" message:@"You did not enter a suffix, such as '.com' or '.net' when typing the website address. You must enter a valid suffix. Please try again." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil, nil];
            [alert show];
            return NO;
            [_activity stopAnimating];
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            
        }


{
    NSString *stringURL = _addressBar.text;
    NSString *stringURLS = _addressBar.text;

    if([[stringURLS uppercaseString] hasPrefix:@"HTTP://"] || [[stringURLS uppercaseString] hasPrefix:@"HTTPS://"] ){}
    else if(![[stringURLS uppercaseString] hasPrefix:@"HTTP://"]) {
        
        NSString *test = [stringURLS uppercaseString];
        
        stringURLS = [@"http://" stringByAppendingString:stringURLS];
        
    };
    
    NSURL *url = [NSURL URLWithString: stringURLS];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:request];
    [_addressBar resignFirstResponder];
    return YES;
}
}



- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    

    NSString *address = [@"https://www.google.com/search?source=ig&hl=en&rlz=&q=" stringByAppendingString:_searchField.text];
    NSString *finalString = [address stringByReplacingOccurrencesOfString:@" " withString: @"+"];
    NSURL *url = [NSURL URLWithString:finalString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [_webView loadRequest:request];
    [_addressBar setText:address];
    [_searchField resignFirstResponder];
    
    
}

-(IBAction)search:(id)sender {
    NSURL *url = [NSURL URLWithString:_addressBar.text];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:request];
    [_addressBar resignFirstResponder];
    
}

- (void) setBackForwardButtonState{
    
    
    [self.buttonBack setEnabled:[_webView canGoBack]];
    [_addressBar setText:[[_webView.request URL] absoluteString]];
    
    [self.buttonForward setEnabled:[_webView canGoForward]];
    [_addressBar setText:[[_webView.request URL] absoluteString]];
    
    
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
 
    if ([segue.identifier isEqualToString:@"segueHistory"]){
        
        
        [(IDGWBHistoryViewController *) segue.destinationViewController setArrayHistory: [_setHistory allObjects]];
        [(IDGWBHistoryViewController *) segue.destinationViewController setArrayHistoryURLS: [_setHistoryURLS allObjects]];
        [(IDGWBHistoryViewController *) segue.destinationViewController setWebViewController:self];
    }
}

-(IBAction)homeButton:(id)sender {
    NSString *address = @"http://www.google.com";
    NSURL *url = [NSURL URLWithString:address];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [_addressBar setText:address];
    [_webView loadRequest:request];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)refreshClicks:(id)sender
{
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[@"" stringByAppendingString:[_addressBar text]]]]];
}

- (IBAction)buttonSettings:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Stainless Browser" message:@"The 'Preferences' feature will be coming soon and is currently not available." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil,nil,nil];
    [alert show];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  [_setHistory count];
}

- (void) goBack: (id)sender{
    [_webView goBack];
}
- (void) goForward: (id)sender{
    [_webView goForward];
}


-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    //You must change 0 to another integer value in the case that UIAlertView includes more than one button.
    
    if (buttonIndex == 0) {
        
        [alertView dismissWithClickedButtonIndex:0 animated:YES];
        [_activity stopAnimating];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
    }
    else
    {
        [alertView dismissWithClickedButtonIndex:0 animated:YES];
        [_activity stopAnimating];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    }
}



@end